from django.shortcuts import render, redirect
from myapp.utils.Pagination import Pagination
from myapp import models
# Create your views here.

from myapp.utils.form import UserModelForm


def user_list(request):
    user_set = models.Userinfo.objects.all()
    # for item in user_set:
    #     print(item.create_time.strftime('%Y-%m-%d'),item.get_gender_display(),item.depart.title)
    # 使用分页组件
    user_page = Pagination(request,query_set=user_set)  #将需分页数据拿出
    user_set = user_page.data_queryset #单页数据
    page_str = user_page.html()# 翻页标签

    return render(request, 'user_list.html', {"user_set": user_set,'page_str':page_str})


def user_add(request):
    if request.method == 'GET':
        choice_dict = {
            'gender_choice': models.Userinfo.gender_choices,
            'depart_choice': models.Department.objects.all()
        }
        return render(request, 'user_add.html', choice_dict)
    name = request.POST.get('name')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    act = request.POST.get('act')
    crtime = request.POST.get('crtime')
    gender = request.POST.get('gender')
    depart = request.POST.get('depart')
    models.Userinfo.objects.create(name=name, password=pwd, age=age,
                                   account=act, create_time=crtime,
                                   gender=gender, depart_id=depart)
    return redirect('/user/list')


def user_model_form_add(request):
    """添加用户（ModelForm版本）"""
    if request.method == 'GET':
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {'form': form})
    # 用户POST提交数据，数据的校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():  # 如果数据合法，保存到数据库
        #  print(form.cleaned_data)
        # {'name': '王帅哥', 'password': '123', 'age': 22, 'account': Decimal('1'),
        #  'create_time': datetime.datetime(2011, 12, 22, 0, 0, tzinfo= < UTC >), 'gender': 1, 'depart': < Department: IT部 >}
        form.save()
        return redirect('/user/list/')
    else:
        print(form.errors)
        return render(request, 'user_model_form_add.html', {'form': form})


def user_update(request, nid):
    """用户更新"""
    row_obj = models.Userinfo.objects.filter(id=nid).first()
    if request.method == "GET":
        form = UserModelForm(instance=row_obj)
        return render(request, 'user_update.html', {'form': form})
    form = UserModelForm(data=request.POST, instance=row_obj)
    if form.is_valid():
        form.save()  # 默认保存用户输入的所有数据
        return redirect('/user/list/')
    return render(request, 'user_update.html', {'form': form})


def user_delete(request, nid):
    """用户删除"""
    models.Userinfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')
